package org.tea.crawl.biz.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.PriorityQueue;

/**
 * @author lxh
 */
public abstract class CommonTools {

    private final static String YYYY = "yyyy";

    private final static String YYYY_MM = "yyyy-MM";

    private final static String YYYY_MM_DD = "yyyy-MM-dd";

    private final static String YYYY_MM_DD_TIME = "yyyy-MM-dd HH:mm:ss";

    private final static PriorityQueue<String> FORMAT_PQ = new PriorityQueue<>((a, b) -> {
        if (a == null && b == null) return 0;
        if (a == null) return -1;
        if (b == null) return 1;
        return a.length() - b.length();
    });

    static {
        FORMAT_PQ.add(YYYY);
        FORMAT_PQ.add(YYYY_MM);
        FORMAT_PQ.add(YYYY_MM_DD);
        FORMAT_PQ.add(YYYY_MM_DD_TIME);
    }

    public static Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) return null;
        if (dateStr.contains("T")) {
            dateStr = dateStr.replaceAll("T", " ");
        }
        Iterator<String> iterator = FORMAT_PQ.iterator();
        while (iterator.hasNext()) {
            String template = iterator.next();
            SimpleDateFormat format = new SimpleDateFormat(template);
            try {
                return format.parse(dateStr);
            } catch (ParseException e) {
                // ignore no match pattern
            }
        }
        throw new IllegalArgumentException("非法的日期格式字符串：" + dateStr);
    }
}
